<template>
  <div class="announcement-admin">
    <el-card>
      <div slot="header" class="card-header">
        <span>公告管理</span>
        <el-button type="primary" @click="showAddDialog">发布公告</el-button>
      </div>

      <el-table :data="announcements" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="标题" width="200"></el-table-column>
        <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="创建人" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="mini" type="danger" @click="deleteAnnouncement(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="form.content" 
            :rows="6"
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>


export default {
  name: 'AnnouncementList',
  data() {
    return {
      announcements: [],
      dialogVisible: false,
      dialogTitle: '发布公告',
      isEdit: false,
      form: {
        id: null,
        title: '',
        content: '',
        status: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadAnnouncements()
  },
  methods: {
    // 加载公告列表
    loadAnnouncements() {
      this.$http.get('/announcement/admin/list').then(result => {
        let R = result.data;
        if (R.code === 2000) {
          this.announcements = R.data || [];
        } else {
          this.$message.error(R.msg || '获取公告列表失败');
        }
      }).catch(error => {
        console.error('获取公告列表失败:', error);
        this.$message.error('获取公告列表失败');
      });
    },

    // 显示新增对话框
    showAddDialog() {
      this.isEdit = false
      this.dialogTitle = '发布公告'
      this.form = {
        id: null,
        title: '',
        content: '',
        status: 1
      }
      this.dialogVisible = true
    },

    // 显示编辑对话框
    showEditDialog(row) {
      this.isEdit = true
      this.dialogTitle = '编辑公告'
      this.form = {
        id: row.id,
        title: row.title,
        content: row.content,
        status: row.status
      }
      this.dialogVisible = true
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const url = this.isEdit ? '/announcement/update' : '/announcement/add';
          this.$http.post(url, this.form).then(result => {
            let R = result.data;
            if (R.code === 2000) {
              this.$message.success(R.msg || '操作成功');
              this.dialogVisible = false;
              this.loadAnnouncements();
            } else {
              this.$message.error(R.msg || '操作失败');
            }
          }).catch(error => {
            console.error('操作失败:', error);
            this.$message.error('操作失败');
          });
        }
      });
    },

    // 切换状态
    toggleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1;
      this.$http.post(`/announcement/status/${row.id}/${newStatus}`).then(result => {
        let R = result.data;
        if (R.code === 2000) {
          this.$message.success('状态更新成功');
          this.loadAnnouncements();
        } else {
          this.$message.error(R.msg || '状态更新失败');
        }
      }).catch(error => {
        console.error('状态更新失败:', error);
        this.$message.error('状态更新失败');
      });
    },

    // 删除公告
    deleteAnnouncement(row) {
      this.$confirm('确定要删除这条公告吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post(`/announcement/delete/${row.id}`).then(result => {
          let R = result.data;
          if (R.code === 2000) {
            this.$message.success('删除成功');
            this.loadAnnouncements();
          } else {
            this.$message.error(R.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        // 取消删除
      });
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.announcement-admin {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
}
</style> 